package com.zdp.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdp.seckill.mapper.PromoMapper;
import com.zdp.seckill.pojo.Promo;
import com.zdp.seckill.pojo.vo.PromModel;
import com.zdp.seckill.service.PromoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author sesshomaru
 * @date 2021/6/19 21:54
 */
@Service
public class PromoServiceImpl implements PromoService {

    @Autowired
    private PromoMapper promoMapper;

    @Override
    public PromModel getPromModelByItemId(Integer itemId) {
        QueryWrapper<Promo> promoQueryWrapper = new QueryWrapper<>();
        promoQueryWrapper.eq("item_id", itemId);
        Promo promo = promoMapper.selectOne(promoQueryWrapper);
        PromModel promModel = convertFromDataObject(promo);
        // 判断当前时间是否秒杀活动即将开始或正在进行
        LocalDateTime endDate = promModel.getEndDate();
        LocalDateTime startDate = promModel.getStartDate();
        if (startDate.isAfter(LocalDateTime.now())) {
            promModel.setStatus(1);
        } else if (endDate.isBefore(LocalDateTime.now())) {
            promModel.setStatus(3);
        }  else {
            promModel.setStatus(2);
        }

        return promModel;
    }

    private PromModel convertFromDataObject(Promo promo) {
        if (promo == null) {
            return null;
        }
        PromModel promModel = new PromModel();
        BeanUtils.copyProperties(promo, promModel);
        return promModel;
    }
}
